let xhr;
const baseURL = "";
let params = {};
$(document).ready(function () {
  const tomorrow = new Date(new Date().getTime() + 1000 * 3600 * 24);
  $("#expiryTime").val(dateFormat("YYYY-mm-dd", tomorrow));
  $("#expiryTime")[0].setAttribute("min", dateFormat("YYYY-mm-dd", tomorrow))
  $("#code").bind("input", debounce(onInput, 1000));
  $(".submit-btn").bind('click', generate)
});

function onInput() {
  const code = $(this).val();
  if (code) {
    getParams(code);
  }
}

function getParams(code) {
  if (xhr) {
    xhr.abort();
    xhr = null;
  }

  $(".loading").show();
  xhr = $.ajax({
    url: baseURL + "/decode",
    method: "post",
    dataType: "json",
    data: { code },
    success(res) {
      if(res.code !== 200) {
        alert("申请码错误");
        return;
      }

      params = res.data.params;

      let html = "";
      Object.entries(params).forEach(([key, type]) => {
        let inputType = {
          "java.util.Date": "date",
          "java.lang.String": "text",
          "java.lang.Integer": "number",
          "java.lang.Long": "number",
        }[type];

        if (!inputType) inputType = "text";

        html += `
          <div class="mb-3 row">
            <label for="${key}" class="col-2 form-label">
              <span class="required">*</span>
            ${key}:</label>
            <div class="col-10">
              <input class="form-control" type="${inputType}"  name="registerParam.licenseAuthParams.${key}" id="${key}" required ${inputType === "number" ? "min='0'" : ""}/>
                <div class="invalid-feedback">
                    请输入${key}
                </div>
            </div>
          </div>
        `;
      });
      $(".detail").html(html);
    },
    complete() {
      $(".loading").hide();
    }
  });
}

function generate(e) {
  e.preventDefault();
  let valid = $("form")[0].checkValidity();
  $("form")[0].classList.add('was-validated')
  if(!valid) return;

  const code = $("#code").val()
  const expiryTime = $("#expiryTime").val()

  const paramList = Object.keys(params).reduce((res, key) => {
    res[key] = $("#" + key).val() || ""
    return res;
  }, {})

  // 模拟表单提交同步方式下载文件
  // 能够弹出保存文件对话框
  const url = baseURL + "/generate";
  var form = $("<form></form>").attr("action", url).attr("method", "post");
  form.append($("<input></input>").attr("type", "hidden").attr("name", "expiryTime").attr("value", expiryTime));
  form.append($("<input></input>").attr("type", "hidden").attr("name", "code").attr("value", code));

  Object.keys(params).forEach(param => {
    form.append($("<input></input>").attr("type", "hidden").attr("name", `params.${param}`).attr("value", paramList[param]));
  })

  form.appendTo('body').submit().remove();
}
